//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ruoyi.system.controller;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.domain.vo.UserVo;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping({"/user"})
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysPostService postService;
    @Autowired
    private ISysPermissionService permissionService;
    @Autowired
    private ISysConfigService configService;

    public SysUserController() {
    }

    @RequiresPermissions({"system:user:list"})
    @PostMapping({"/list"})
    public TableDataInfo list(@RequestBody SysUser user) {
        PageDomain pageDomain = new PageDomain();
        BeanUtils.copyProperties(user, pageDomain);
        this.startPage(pageDomain);
        List<SysUser> list = this.userService.selectUserList(user);
        return this.getDataTable(list);
    }

    @Log(
            title = "用户管理",
            businessType = BusinessType.EXPORT
    )
    @RequiresPermissions({"system:user:export"})
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = this.userService.selectUserList(user);
        Iterator var4 = list.iterator();

        while(var4.hasNext()) {
            SysUser sysUser = (SysUser)var4.next();
            sysUser.setTime(sysUser.getCreateTime());
        }

        ExcelUtil<SysUser> util = new ExcelUtil(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(
            title = "用户管理",
            businessType = BusinessType.IMPORT
    )
    @RequiresPermissions({"system:user:import"})
    @PostMapping({"/importData"})
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = this.userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping({"/importTemplate"})
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    @InnerAuth
    @GetMapping({"/info/{username}"})
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = this.userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        } else {
            Set<String> roles = this.permissionService.getRolePermission(sysUser);
            Set<String> permissions = this.permissionService.getMenuPermission(sysUser);
            LoginUser sysUserVo = new LoginUser();
            sysUserVo.setSysUser(sysUser);
            sysUserVo.setRoles(roles);
            sysUserVo.setPermissions(permissions);
            return R.ok(sysUserVo);
        }
    }

    @InnerAuth
    @PostMapping({"/register"})
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!"true".equals(this.configService.selectConfigByKey("sys.account.registerUser"))) {
            return R.fail("当前系统没有开启注册功能！");
        } else {
            return "1".equals(this.userService.checkUserNameUnique(username)) ? R.fail("保存用户'" + username + "'失败，注册账号已存在") : R.ok(this.userService.registerUser(sysUser));
        }
    }

    @GetMapping({"getInfo"})
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = this.userService.selectUserById(userId);
        Set<String> roles = this.permissionService.getRolePermission(sysUser);
        Set<String> permissions = this.permissionService.getMenuPermission(sysUser);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", sysUser);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    @RequiresPermissions({"system:user:query"})
    @GetMapping({"/getInfoByUserId"})
    public AjaxResult getInfo(Long userId) {
        this.userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = this.roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter((r) -> {
            return !r.isAdmin();
        }).collect(Collectors.toList()));
        ajax.put("posts", this.postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = this.userService.selectUserById(userId);
            ajax.put("data", sysUser);
            ajax.put("postIds", this.postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }

        return ajax;
    }

    @RequiresPermissions({"system:user:add"})
    @Log(
            title = "用户管理",
            businessType = BusinessType.INSERT
    )
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if ("1".equals(this.userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && "1".equals(this.userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && "1".equals(this.userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        } else {
            user.setCreateBy(SecurityUtils.getUsername());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            return this.toAjax(this.userService.insertUser(user));
        }
    }

    @RequiresPermissions({"system:user:edit"})
    @Log(
            title = "用户管理",
            businessType = BusinessType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        this.userService.checkUserAllowed(user);
        this.userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && "1".equals(this.userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && "1".equals(this.userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        } else {
            user.setUpdateBy(SecurityUtils.getUsername());
            return this.toAjax(this.userService.updateUser(user));
        }
    }

    @PostMapping({"editUserInfo"})
    @Log(
            title = "修改用户信息",
            businessType = BusinessType.UPDATE
    )
    public AjaxResult editUserInfo(@RequestBody SysUser sysUser) {
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        return this.toAjax(this.userService.editUserInfo(sysUser));
    }

    @RequiresPermissions({"system:user:editLockStatus"})
    @Log(
            title = "修改用户信息",
            businessType = BusinessType.UPDATE
    )
    @PostMapping({"editLockStatus"})
    public AjaxResult editLockStatus(@RequestBody SysUser user) {
        return this.userService.editLockStatus(user);
    }

    @RequiresPermissions({"system:user:remove"})
    @Log(
            title = "用户管理",
            businessType = BusinessType.DELETE
    )
    @PostMapping({"/remove"})
    public AjaxResult remove(@RequestBody Long[] userIds) {
        return ArrayUtils.contains(userIds, SecurityUtils.getUserId()) ? AjaxResult.error("当前用户不能删除") : this.toAjax(this.userService.deleteUserByIds(userIds));
    }

    @RequiresPermissions({"system:user:edit"})
    @Log(
            title = "用户管理",
            businessType = BusinessType.UPDATE
    )
    @PostMapping({"/resetPwd"})
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        this.userService.checkUserAllowed(user);
        this.userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return this.toAjax(this.userService.resetPwd(user));
    }

    @Log(
            title = "用户管理",
            businessType = BusinessType.UPDATE
    )
    @PostMapping({"/update"})
    public AjaxResult exitUser(@RequestBody SysUser user) {
        return this.toAjax(this.userService.updateUser1(user));
    }

    @Log(
            title = "修改密码",
            businessType = BusinessType.UPDATE
    )
    @PostMapping({"/editPwd"})
    public AjaxResult editPwd(@RequestBody SysUser user) {
        return this.userService.editPwd(user);
    }

    @RequiresPermissions({"system:user:edit"})
    @Log(
            title = "用户管理",
            businessType = BusinessType.UPDATE
    )
    @PostMapping({"/changeStatus"})
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        this.userService.checkUserAllowed(user);
        this.userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return this.toAjax(this.userService.updateUserStatus(user));
    }

    @RequiresPermissions({"system:user:query"})
    @GetMapping({"/authRoleByUserId"})
    public AjaxResult authRole(Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = this.userService.selectUserById(userId);
        List<SysRole> roles = this.roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter((r) -> {
            return !r.isAdmin();
        }).collect(Collectors.toList()));
        return ajax;
    }

    @RequiresPermissions({"system:user:edit"})
    @Log(
            title = "用户管理",
            businessType = BusinessType.GRANT
    )
    @PostMapping({"/authRole"})
    public AjaxResult insertAuthRole(@RequestBody UserVo userVo) {
        this.userService.checkUserDataScope(userVo.getUserId());
        this.userService.insertUserAuth(userVo.getUserId(), userVo.getRoleIds());
        return this.success();
    }

    @GetMapping({"/findById"})
    public SysUser getInfoById(@RequestParam Long userId) {
        SysUser sysUser = null;
        if (StringUtils.isNotNull(userId)) {
            sysUser = this.userService.selectUserById(userId);
        }

        return sysUser;
    }
}
